<?php
namespace app\store\controller;
use app\store\model\Wxapp as WxappModel;
use app\store\model\Config as ConfigModel;
use app\store\model\UploadFile as UploadFileModel;
use app\store\model\StoreApply as StoreApplyModel;
use think\Cache;

/**
 * 小程序管理
 */
class Wxapp extends Controller
{
	/**
     * 小程序设置
     */
    public function setting()
    {
        $wxapp = WxappModel::detail();
		$auth = StoreApplyModel::getDetail(['wxapp_id' => $this->wxapp_id]);//注册信息
		$config = ConfigModel::detail();
		$url = authUrl($config['app_id'],$config['component_access_token'],2);//获取授权页面地址
		$wxapp['serve_domain'] = $config['api_domain'];//获取最新服务器域名列表
        if ($this->request->isAjax()) {
        	//全局判断
			if($err = checking(1)){
				return $this->renderError($err);
			}
            if ($wxapp->edit($this->postData('wxapp'))){
            	return $this->renderSuccess('更新成功');
            }
            return $this->renderError('更新失败');
        }
		//如果授权给第三方了，则获取
		$infor = [];
		if($wxapp['is_empower']['value']==1){
			$infor = $this->getInfor(); //服务端 - 小程序设置信息
		}
        return $this->fetch('setting', compact('wxapp','infor','auth','url'));
    }

	/**
     * 生成体验版二维码
     */
	public function testCode($wxapp_id)
	{
		$access_token = getAccessToken();
		$path = urlencode('/pages/index/index');
		$url = 'https://api.weixin.qq.com/wxa/get_qrcode?access_token='.$access_token.'&path='.$path;
		$result = curl($url);
		$path = 'assets/qrcode/wxapp';
		if(!file_exists($path)){
			mkdir($path,0777,true);
		}
		file_put_contents($path . '/'.$wxapp_id.'_test.png',$result); //获取的二维码数据存储到指定的文件
		$this->redirect('/' . $path . '/'.$wxapp_id.'_test.png');
	}

    /**
     * 设置业务域名
     */
    public function setdomain()
    {
		
    	$model = WxappModel::detail();
        if ($this->request->isAjax()) {
        	if($this->store['wxapp']['is_empower']['value']==0){
	            return $this->renderError('请先绑定您的微信小程序', url('wxapp/setting'));
			}
        	$wxapp = $this->postData('wxapp');
        	$access_token = getAccessToken();
			$url = 'https://api.weixin.qq.com/wxa/setwebviewdomain?access_token='.$access_token;
			$data = [
				'action' => 'set',
				'webviewdomain' => explode(';',$wxapp['webview_domain'])
			];
			$result = json_decode(http_post($url,$data),true);
			if($result['errcode']!=0){
				return $this->error(wx_err_msg($result['errcode']));
			}
            if ($model->edit($wxapp)){
            	return $this->renderSuccess('设置成功');	
            }
            return $this->renderError('设置失败');
        }
        return $this->fetch('setdomain', compact('model'));
    }
	
	/**
     * 设置头像
     */
    public function sethead()
    {
        $wxapp = WxappModel::detail();
        if ($this->request->isAjax()) {
        	//全局判断
			if($err = checking(1)){
				return $this->renderError($err);
			}
			$app = $this->postData('wxapp');
			if(empty($app['head_img'])){
				return $this->renderError('请选择一个头像图片');
			}else{
				
				//上传临时素材
				$media_id = up_temp_material($app['head_img']);
				$access_token = getAccessToken();
				//执行修改头像
				$url = 'https://api.weixin.qq.com/cgi-bin/account/modifyheadimage?access_token='.$access_token;
				$data = [
					'head_img_media_id' => $media_id,
					'x1' => 0,
					'y1' => 0,
					'x2' => 1,
					'y2' => 1
				];
				$result = json_decode(http_post($url,$data),true);
				if($result['errcode']!=0){
					return $this->renderError(wx_err_msg($result['errcode']));
				}
				$app['head_img'] = '/uploads/'.$app['head_img']; 
				if ($wxapp->edit($app)){
					return $this->renderSuccess('设置成功', url('wxapp/setting'));
				}
				return $this->renderError('设置失败');
				
			}
        }
        return $this->fetch('sethead', compact('wxapp'));
    }
	
	
	/**
	* 查询昵称设置状态
	*/
	public function querynickname(){
		$audit_id='454738159';
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/wxa/api_wxa_querynickname?access_token='.$access_token;
		$data = ['audit_id' => $audit_id];
		$result = http_post($url,$data);
		return $result;
	}
	
	/**
	* 获取附近小程序 - 服务类目
	*/
	public function nearby(){
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/wxa/get_merchant_category?access_token='.$access_token;
		$result = json_decode(curl($url),true);
		return $result;
	}
	
	/**
	* 获取小程序设置信息
	*/
	public function getInfor(){
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/cgi-bin/account/getaccountbasicinfo?access_token='.$access_token;
		$result = json_decode(curl($url),true);
		return $result;
	}
	
	/**
	* 获取审核时可填写的类目信息
	*/
	public function getshowwxaitem()
	{
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/wxa/getshowwxaitem?access_token='.$access_token;
		return curl($url);
	}
	
	/**
     * 同步小程序信息
     */
    public function update($app_id)
    {
		$config = ConfigModel::detail();
		//获取授权应用的帐号基本信息
		$result = getAppInfo($app_id, $config['app_id'], $config['component_access_token']);
		$app = $result['authorizer_info'];//得到授权应用的帐号基本信息
		$wxapp = WxappModel::detail(); //获取商户数据
		$wxapp->edit([
			'app_name' => isset($app['nick_name'])?$app['nick_name']:'',	//昵称
			'head_img' => isset($app['head_img'])?$app['head_img']:'',		//头像
			'qrcode_url' => isset($app['qrcode_url'])?$app['qrcode_url']:'',	//二维码
			'user_name' => $app['user_name'],					//原始ID
			'principal_name' => $app['principal_name'],			//主体名称
			'signature' => isset($app['signature'])?$app['signature']:'',	//账号介绍			
		]);
		//清除缓存
		Cache::rm('wxapp_' . $wxapp['wxapp_id']);
		return $this->renderSuccess('同步成功', url('wxapp/setting'));
	}

	/**
     * 跳转到扫码授权页面
     */
    public function auth()
    {
        $this->success('即将跳转到扫码授权页面',authUrl(2,$this->wxapp_id));
    }

}
